//Copyright (c) 2009, Lawrence Anstey
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//    * Neither the name of Lawrence Anstey nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


using System;
using System.IO;
using System.Xml;

namespace twitsmoke
{
	class MainClass
	{
		//static Twitter tClient;
		static Twitterizer.Framework.Twitter t;
		static string sPath = "/home/hobofood/";
		static string FileName = "config.xml";
		static config config = new config();
		static string logFile = "/home/hobofood/ts.log";
		static StreamWriter log;
		
		public static void Main(string[] args)
		{
			if (File.Exists(logFile)) { File.Delete(logFile); }
			log = new StreamWriter(File.OpenWrite(logFile));
			log.WriteLine("twitsmoke v0.2");
			//tClient = new Twitter();
			t = new Twitterizer.Framework.Twitter("twitsmoke", "smoketwit123");
			
			
			//config config = new config();
			System.Xml.Serialization.XmlSerializer serial;
			serial = new System.Xml.Serialization.XmlSerializer(config.GetType());
			System.IO.FileStream reader = File.OpenRead(sPath + FileName);
			config = (config)serial.Deserialize(reader);
			reader.Close();
			
			log.WriteLine(config.lastupdated.ToString() + " - " + config.quitters.Count.ToString() + " quitters");
			
			TellPeople();
			FindPeople();
						
			//System.Xml.Serialization.XmlSerializationWriter writer = new System.Xml.Serialization.XmlSerializationWriter();
			config.lastupdated = DateTime.Now;
			
			File.Delete(sPath + FileName);
			System.IO.FileStream writer = File.OpenWrite(sPath + FileName);
			
			serial.Serialize(writer, config);
			
			log.Close();
						
		}
		
		
		public static void FindPeople()
		{
			log.WriteLine("Finding new quitters");
			string sRes = "";
			Twitterizer.Framework.TwitterStatusCollection replies = t.Status.Replies();
			log.WriteLine("Found " + replies.Count.ToString() + " replies");
			for (int i = 0; i < replies.Count; i++)
			{
				log.WriteLine("reply " + i + " from " + replies[i].TwitterUser.UserName);
				
				int iOffset = 1;
				
							
				if (replies[i].Created.AddHours(iOffset) < config.lastupdated) {
					//do nothing
					log.WriteLine("reply was created on " + replies[i].Created.ToString() + ", lastupdated is " + config.lastupdated.ToString());
				} else {
				
					if (replies[i].Text.ToUpper().IndexOf("QUIT") > -1) {
						int iUser = findQuitterIndex(replies[i].TwitterUser.UserName);
						if (iUser < 0)
						{
							log.WriteLine("Adding new user");
							quitter q = new quitter();
							q.twitteruser = replies[i].TwitterUser.UserName;
							q.lasttweet = DateTime.Now;
							q.quiton = DateTime.Now;
							q.tweetfrequency = 60;
							config.quitters.Add(q);
							t.Status.Update("@" + q.twitteruser + " Good luck!");
						} else {
							log.WriteLine("User is already registered");
							//t.Status.Update("@" + config.quitters[i].twitteruser + " You are already registered!");
						}
					} else if (replies[i].Text.ToUpper().IndexOf("SORRY") > -1) {
						int iUser = findQuitterIndex(replies[i].TwitterUser.UserName);
						if (iUser < 0)
						{
							log.WriteLine("quitter " + replies[i].TwitterUser.UserName + " not found");
							t.Status.Update("@" + config.quitters[i].twitteruser + " you don't seem to be a registered user. Register by sending '@twitsmoke I QUIT'");
						} else {
							log.WriteLine("resetting quiton to " + DateTime.Now.ToString());
							config.quitters[iUser].quiton = DateTime.Now;
							t.Status.Update("@" + config.quitters[i].twitteruser + " YOU ARE A TERRIBLE HUMAN BEING. TRY AGAIN.");
						}
					} else if (replies[i].Text.ToUpper().IndexOf("FREQUENCY") > -1) {
						log.WriteLine("updating frequency");
						int iUser = findQuitterIndex(replies[i].TwitterUser.UserName);
						if (iUser < 0)
						{
							log.WriteLine("quitter " + replies[i].TwitterUser.UserName + " not found");
							t.Status.Update("@" + config.quitters[i].twitteruser + " you don't seem to be a registered user. Register by sending '@twitsmoke I QUIT'");
						} else {
							
							int iFreq = 60;
							string s = replies[i].Text.ToUpper();
							s = s.Replace("@TWITSMOKE", "");
							s = s.Replace("FREQUENCY", "");
							
							try
							{
								iFreq = int.Parse(s);
								log.WriteLine("setting frequency to " + iFreq.ToString());
								config.quitters[iUser].tweetfrequency = iFreq;
								t.Status.Update("@" + config.quitters[i].twitteruser + " Updated your frequency to every " + iFreq.ToString() + " mins");
							}
							 catch (Exception e)
							{
								log.WriteLine("Got status " + replies[i].Text + " but invalid frequency of " + s + " - " + e.ToString());
								t.Status.Update("@" + config.quitters[i].twitteruser + " " + s + " is not a valid number of minutes.");
							}
									
	
						}
					}
					
				}
				
			}
			log.WriteLine(sRes);
		}
		
		public static int findQuitterIndex(string user)
		{
			int ret = -1;
			for (int i = 0; i < config.quitters.Count; i++) {
				if (config.quitters[i].twitteruser.ToUpper() == user.ToUpper())
				{
					ret = i;
					break;
				}
				
			}
			
			return ret;
			
		}
		
		public static void TellPeople()
		{
			//sPath = Environment.CurrentDirectory();
						
			
			
			for (int i = 0; i < config.quitters.Count; i++) {
				log.WriteLine("Processing quitter " + i.ToString());
//				
//				string user = "";
//				DateTime dtQuit = DateTime.Now;
//				DateTime dtLastTweet = DateTime.Now;
//				int iFrequency = 60;
//				
//				XmlDocument xmld = new XmlDocument();
//				xmld.Load(Files[i]);
//				
//				for (int n = 0; n < xmld.DocumentElement.ChildNodes.Count; n++) {
//					switch (xmld.DocumentElement.ChildNodes[n].Name.ToUpper()) {
//					case "TWITTERUSER":
//						user = xmld.DocumentElement.ChildNodes[n].InnerText;
//						break;
//					case "QUITON":
//						dtQuit = DateTime.Parse(xmld.DocumentElement.ChildNodes[n].InnerText);
//						break;
//					case "LASTTWEET":
//						dtLastTweet = DateTime.Parse(xmld.DocumentElement.ChildNodes[n].InnerText);
//					 	break;
//					case "FREQUENCY":
//						iFrequency = int.Parse(xmld.DocumentElement.ChildNodes[n].InnerText);
//						break;
//					}
//						
//				}
				
				log.WriteLine("User " + config.quitters[i].twitteruser + " quit on " + config.quitters[i].quiton.ToString() + " last tweet was " + config.quitters[i].lasttweet.ToString());
				if (config.quitters[i].lasttweet.AddMinutes(config.quitters[i].tweetfrequency) <= DateTime.Now) {
					log.WriteLine("Tweeting @" + config.quitters[i].twitteruser + " - it has been more than " + config.quitters[i].tweetfrequency + "mins");	
					string sUpdate = "@" + config.quitters[i].twitteruser + " you quit ";
					TimeSpan ts = DateTime.Now.Subtract(config.quitters[i].quiton);
					if (ts.Days >= 1) {
						sUpdate += ts.Days.ToString() + " days, " + ts.Hours + " hours ago!";
					} else {
						sUpdate += ts.Hours.ToString() + " hours, " + ts.Minutes + " mins ago!";
					}
					
					string sRes = "";
					
					log.WriteLine("updating with: " + sUpdate);
					
					t.Status.Update(sUpdate);
					
					config.quitters[i].lasttweet = DateTime.Now;
					
					//sRes = tClient.Update("twitsmoke", "smoketwit123", sUpdate, Yedda.Twitter.OutputFormatType.XML);		
					
					log.WriteLine("Done");
					
				} else {
					log.WriteLine(config.quitters[i].lasttweet.AddMinutes(config.quitters[i].tweetfrequency) + " is too soon");	
				}
				
			}
			//tClient.Update("twitsmoke", "smoketwit", "", OutputFormatType.What);
			
		}
	}
}